<template>
    <div class="front-padding subsidiaryLedger1">
        <div class="widgets bg-white">
            <div class="left">
                <el-input v-model="searchText" placeholder="输入搜索内容" class="search__input" @keyup.enter.native="search"></el-input>
                <el-button type="primary" @click="search">查询</el-button>
            </div>
            <div class="btn-group right">
                <el-button type="info" @click="refData">刷新</el-button>
                <el-button type="primary" v-if="radioState == 1 || $store.state.initializeVal[0]['subAssertList'].length > 0" disabled>新增</el-button>
                <el-button type="primary" v-else @click="addRow">新增</el-button>
                <el-button type="danger" v-if="radioState == 1 || $store.state.initializeVal[0]['subAssertList'].length > 0" disabled>删除</el-button>
                <el-button type="danger" v-else @click.native.prevent="deleteRow(subSidiaryRowId)">删除</el-button>
                <el-button type="primary" v-if="radioState == 1 || $store.state.initializeVal[0]['subAssertList'].length > 0" disabled>保存</el-button>
                <el-button type="primary" v-else @click="saveSubsidiary()">保存</el-button>
                <el-button-group class="btn-other">
                    <el-button title="导出" @click="exportExal">
                        <img src="../../../assets/images/export.png" alt="">
                    </el-button>
                    <el-button title="打印">
                        <img src="../../../assets/images/print.png" alt="">
                    </el-button>
                    <el-button title="帮助">
                        <img src="../../../assets/images/help.png" alt="">
                    </el-button>
                </el-button-group>
            </div>
        </div>
        <div class="table bg-white bj">
            <el-scrollbar style="height: 100%;">
                <el-table :data="subsidiaryRow" border @selection-change="handleSelectionChange">
                    <el-table-column type="selection" align="center"></el-table-column>
                    <el-table-column property="type" label="类别">
                        <template slot-scope="scope">
                            <el-select v-model="scope.row.type" ref="MA28"  @change="getSelectObj(scope.row.type,scope.$index)" placeholder="选择类别" style="height: 32px;line-height:32px">
                                <el-option v-for="(items, index) in categoryData"  :label="items.name" :value="items.id" :key="index"></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column property="name" label="名称">
                        <template slot-scope="scope">
                            <el-input size="small" type="text" v-model="scope.row.name" @focus="focus($event)" readonly @click.native="getObjectsData(scope.$index)" placeholder="输入名称"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column property="money" label="金额">
                        <template slot-scope="scope">
                                <el-input size="small" type="number" @focus="focus($event)" v-model="scope.row.money" placeholder="输入金额"></el-input>
                        </template>
                    </el-table-column>
                </el-table>
            </el-scrollbar>
        </div>
    </div>
</template>
<script>
    /**
     * Author: 赵巧芬
     * Date: 2019-3
     * Description: 综合明细账组件
    */
    export default {
        data() {
            return {
                searchText: '',                     //搜索文本
                multipleSelection: [],              //选中的行数据集合
                systemId:'',
                subsidiaryRow: this.$store.state.initializeStore.subsidiaryData,                    //表格数据
                subSidiaryRowId:[],                 //选中表格当前行的id
                categoryData: this.$store.state.initializeStore.categoryData,                       //类别
                objectName: this.$store.state.initializeStore.objectName,   //存储往来对象名称
                rowIndex: '',                       //点击明细账名称获取当前索引
                searchAllResultTwo: this.$store.state.initializeStore.searchAllResultTwo,           //明细账搜索
                radioState: '',                     //启用系统状态
                tag: '',                            //判断类别
                selectName: this.$store.state.initializeStore.selectName,
            }
        },
        watch: {
            //监听往来对象名称弹窗选中的名称
            objectName(){
                if(this.objectName.length > 0){
                    for(let i = 0;i < this.subsidiaryRow.length;i++){
                        //如果点击当前名称的索引与表格数据的索引一致
                        if(i == this.rowIndex){
                            //则将选中的名称赋给选中的表格数据
                            this.subsidiaryRow[i]['number'] = this.objectName[0]['id'];
                            this.subsidiaryRow[i]['name'] = this.objectName[0]['name'];
                            
                            if(this.$store.state.initializeStore.selectName == '职员'){
                                this.subsidiaryRow[i]['tag'] = 0;
                            }else if(this.$store.state.initializeStore.selectName == '客户分类'){
                                this.subsidiaryRow[i]['tag'] = 1;
                            }else if(this.$store.state.initializeStore.selectName == '供应商分类'){
                                this.subsidiaryRow[i]['tag'] = 2;
                            }
                        }
                    }
                }
            },
            //监听搜索框内容
            searchText(newVal) {
                if(!newVal) {
                    this.subsidiaryRow = this.$store.state.initializeStore.subsidiaryData;
                }
            },
        },
        methods: {
            currency(moneyA){                       //过滤金额
                if (moneyA && moneyA != null) {
                    moneyA = String(moneyA);
                    var left = moneyA.split('.')[0], right = moneyA.split('.')[1];
                    right = right ? (right.length >= 2 ? '.' + right.substr(0, 2) : '.' + right + '0') : '.00';
                    var temp = left.split('').reverse().join('').match(/(\d{1,3})/g);
                    return (Number(moneyA) < 0 ? '-' : '') + temp.join(',').split('').reverse().join('') + right;
                    } else if (moneyA === 0) { // 注意===在这里的使用，如果传入的moneyA为0,if中会将其判定为boolean类型，故而要另外做===判断
                    return '0.00';
                    } else {
                    return '';
                }
            },
            handleSelectionChange(val) {            //点击表格选中触发
                this.multipleSelection = val;
                this.subSidiaryRowId = [];
                this.selectRowId = [];
                for(var i = 0; i < this.multipleSelection.length; i++) {
                    this.selectRowId.push(this.multipleSelection[i]['id']);
                    this.subSidiaryRowId.push(this.multipleSelection[i]['id']);
                }
            },
            focus(event) {                          //得到焦点选中
                event.currentTarget.select();
            },
            refData(){                              //刷新
                const loading = this.$loading({
                    lock: true,
                    text: '数据刷新中...',
                    spinner: 'el-icon-loading',
                    background: '#fff'
                });
                setTimeout(() => {
                    loading.close();
                }, 1000);
            },
            deleteRow($id) {                        //批量删除
                if(this.multipleSelection.length > 0) {
                    this.$confirm('确定删除该条数据?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        var type = {
                            headers: {
                                'Content-type': 'application/json;charset=UTF-8'
                            }
                        }
                        this.$http.post(this.$url + 'betweenObject/batchInsertObject', JSON.stringify(this.subSidiaryRowId), type).then(res => {
                            if(res.data.code == 20001) {
                                this.$message({message: '删除成功', type: 'success', duration: 2000});
                                this.$store.dispatch('initializeStore/getSubsidiaryData', this.$url + 'betweenObject/selectObjectById?subejctId='+this.$store.state.initializeVal[0]['id']);
                                setTimeout(() => {
                                    this.getMoneySum(this.$store.state.initializeStore.subsidiaryData);
                                },500);
                            } else {
                                this.$message.error(res.data.msg);
                            }
                        });
                    })
                }else{
                    this.$message({message: '请先选择你要删除的数据', type: 'warning'});
                }
            },
            deleteSingleRow($id) {                  //删除单条明细
                this.$confirm('确定删除该条数据？', '删除提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var type = {
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    }
                    //开始求删除
                    this.$http.post(this.$url + 'betweenObject/batchInsertObject', JSON.stringify([$id]), type).then(res => {
                        if(res.data.code == 20001) {
                            this.$message({message: '删除成功', type: 'success', duration: 2000});
                            this.$store.dispatch('initializeStore/getSubsidiaryData', this.$url + 'betweenObject/selectObjectById?subejctId='+this.$store.state.initializeVal[0]['id']);
                            setTimeout(() => {
                                this.getMoneySum(this.$store.state.initializeStore.subsidiaryData);
                            },500);
                        } else {
                            this.$message.error(res.data.msg);
                        }
                    });
                });
            },
            addRow(){                               //新增
                if(this.categoryData.length > 0){
                    this.subsidiaryRow.push({type:this.categoryData[0]['id'],name:'',number:'',money:''})
                }else{
                    this.subsidiaryRow.push({type:'',name:'',number:'',money:''})
                }
            },
            getSelectObj(val,index){                //如果类别更改
                let obj = {};
                obj = this.categoryData.find((item)=>{
                    return item.id === val;
                });
                let getName = ''
                getName = obj.name;
                this.$store.commit('initializeStore/setSelectObj', getName);
                for(let i = 0;i < this.subsidiaryRow.length;i++){//当类别更改，将名称清空
                    if(i == index){
                        this.subsidiaryRow[i]['name'] = '';
                    }
                }
            },
            getObjectsData(index) {                 //显示名称弹窗
                this.rowIndex = index;
                for(let i = 0;i < this.subsidiaryRow.length;i++){
                    if(i == index){
                        for(let j = 0;j < this.categoryData.length;j++){
                            if(this.subsidiaryRow[i]['type'] == this.categoryData[j]['id']){
                                if(this.categoryData[j]['name'] == '客户分类'){
                                    this.$util.openLayerIframe({title: '往来对象', zIndex: 13, width: '450px', height: '360px', url: this.$domain + '/#/initialize/objects'});
                                }else if(this.categoryData[j]['name'] == '供应商分类'){
                                    this.$util.openLayerIframe({title: '往来对象', zIndex: 13, width: '450px', height: '360px', url: this.$domain + '/#/initialize/objectTwo'});
                                }else if(this.categoryData[j]['name'] == '职员'){
                                    this.$util.openLayerIframe({title: '往来对象', zIndex: 13, width: '450px', height: '360px', url: this.$domain + '/#/initialize/objectThree'});
                                }else{
                                    this.$message({message: '请先选择类别',type: 'warning'})
                                }
                            }
                        }
                    }
                }
            },
            getMoneySum(arr){                       //合计金额
                let moneySum = 0;
                if(arr.length > 0){
                    for(let i = 0;i < arr.length;i++){
                        if(arr[i]['money']){
                            moneySum += parseFloat(arr[i]['money']);
                        }
                    }
                    this.$store.commit('initializeStore/setSubSidiaryMoneySum', moneySum)
                }else{
                    this.$store.commit('initializeStore/setSubSidiaryMoneySum', moneySum)
                }
            },
            saveSubsidiary(){                       //明细账保存
                var type = {
                    headers: {
                        'Content-type': 'application/json;charset=UTF-8'
                    }
                }
                if(this.subsidiaryRow.length > 0){
                    let Arr = this.subsidiaryRow.map(obj => {
                        return {
                            subjectId: this.$store.state.initializeVal[0]['id'],
                            type: obj['type'],
                            number: obj['number'],
                            money: obj['money'],
                            tag: obj['tag']
                        }
                    });
                    let newArr = [];
                    for(let i = 0;i < Arr.length;i++){
                        if(Arr[i]['type'] !== '' && Arr[i]['number'] !== ''){
                            newArr.push(Arr[i]);
                        }
                    }
                    this.$http.post(this.$url + 'betweenObject/saveObject', JSON.stringify(newArr), type).then(res => {
                        if(res.data.code == 20001){
                            this.$message({message: '保存成功', type: 'success'});
                            setTimeout(() => {
                                this.$store.dispatch('initializeStore/getSubsidiaryData', this.$url + 'betweenObject/selectObjectById?subejctId='+this.$store.state.initializeVal[0]['id']);
                            });
                            this.getMoneySum(this.subsidiaryRow);
                            this.$store.commit('initializeStore/updateIsSave', true);
                        }
                    });
                }else{
                    this.$message({message: '保存失败', type: 'warning'});
                }
                
            },
            exportExal(){                           //导出
                if(this.multipleSelection.length > 0) {
                    var idSting = this.selectRowId.join(',');           //将[1,2,3]格式转为 "1,2,3"
                    this.$http.get(this.$url + 'betweenObject/exportThird',{params: { list: idSting }}).then(res => {
                        this.$message({message: '导出成功', type: 'success'});
                        window.location.href = this.$url + 'betweenObject/exportThird?list=' + idSting;          //导出时触发
                    }).catch(err => {
                        this.$message.error(err);
                    })
                } else {
                    this.$message({message: '选择你要导出的数据', type: 'warning', duration: 2000});
                }
            },
            search(){                               //搜索
                if(this.searchText) {
                    let newArr = [],
                        data = this.searchAllResultTwo,
                        searchText = this.searchText;
                    let reg = new RegExp(this.searchText, "g");
                    data.forEach(item => {
                        if(reg.test(item['typeName']) || reg.test(item['name']) || reg.test(item['compactCode']) || (reg.test(item['typeName'])) || (reg.test(item['money'])) || (item['toPinyineName'] && reg.test(item['toPinyineName'])) || (item['toPinyinTypeName'] && reg.test(item['toPinyinTypeName'])) || (item['toPinyinCompactCode'] && reg.test(item['toPinyinCompactCode']))) {
                            newArr.push(item);
                        }
                    });
                    this.subsidiaryRow = newArr;
                }
            }
        },
        created() {
            //获取明细账数据
            this.$store.dispatch('initializeStore/getSubsidiaryData', this.$url + 'betweenObject/selectObjectById?subejctId='+this.$store.state.initializeVal[0]['id']);
            setTimeout(() => {
                //获取类别数据
                this.$store.dispatch('initializeStore/getCategoryData', this.$url + 'subjectGroup/selectGroupById?id='+this.$store.state.initializeVal[0]['id']);
            },1000);
            //判断启用系统是否是结束初始化
            let enableStatus = Number(localStorage.getItem('setRadio'));
            enableStatus ? this.radioState = enableStatus : this.radioState = 0;
        }
    }
</script>
<style scoped lang="less">
.subsidiaryLedger1{
    .widgets{min-width: 800px !important;}
    .table{min-width: 800px !important;}
}
</style>

<style lang='less'>
    .subsidiaryLedger1{
        input::-webkit-outer-spin-button,
        input::-webkit-inner-spin-button {
            -webkit-appearance: none;
        }
        input[type="number"] {
            -moz-appearance: textfield;
        }
        .el-input__inner{
            height: 32px !important;
            line-height: 32px !important;
        }
    }
</style>